package com.project.shiro.controller;

import com.project.common.core.utils.exception.BaseCustomException;
import com.project.common.core.utils.exception.Result;
import com.project.shiro.util.AuthenticationToken;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 后台公用controller
 */
@RestController("adminLoginController")
@RequestMapping("/admin")
public class loginController extends BaseController {
    private static final long serialVersionUID = -7624305021416504596L;

    /**
     * shiro登录
     *
     * @return
     */
    @ApiOperation(value = "shiro登录", notes = "shiro登录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "账户名", dataType = "String"),
            @ApiImplicitParam(name = "enPassword", value = "密码", dataType = "String")
    })
    @PostMapping(value = "/login")
    public Result<String> login(String loginName, String enPassword) {
        try {
            Subject subject = SecurityUtils.getSubject();
            AuthenticationToken token = new AuthenticationToken(loginName, enPassword, false, "", "", "");
            subject.login(token);
        } catch (UnknownAccountException e) {
            String msg = "账号不存在";
            throw new BaseCustomException("10090", msg);
        } catch (IncorrectCredentialsException e) {
            String msg = "密码不正确";
            throw new BaseCustomException("10091", msg);
        } catch (AuthenticationException e) {
            String msg = "用户验证失败";
            throw new BaseCustomException("10092", msg);
        }
        return getResult("success");
    }

}
